<?php

namespace App\Http\Controllers;

use App\Models\Group;
use App\Models\Project;
use App\Models\User;
use App\Services\Repo\ProjectRepo;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;

class UserProjectController extends Controller
{
    public function index($user_id) {
        $user = Auth::User();
        if ($user_id !== $user->id) {
            return $this->_error('用户id不合法');
        }
        $results = [];
        $group = Group::find($user->group_id);
        if ($group) {
            $groups = $group->getLeafBy();
            $group_id = [];
            if (is_array($groups)) {
                foreach ($groups as $value) {
                    array_push($group_id, $value->id);
                }
            } else {
                if (!$user->isManager) {
                    return $this->formatList($user);
                }
                array_push($group_id, $groups->id);
            }

            if ($group_id) {
                $projects = Project::whereIn('group_id', $group_id)->get();
                foreach ($projects as $project) {
                    $users = User::select(['_id', 'name', 'status'])
                        ->whereIn('_id', $project->users)
                        ->get();
                    $temp = [];
                    foreach ($users as $user) {
                        array_push($temp,[
                            '_id' => $user->id,
                            'name' => $user->name,
                            'status' => $user->status, 
                        ]);
                    }
                    $project->users = $temp;
                    array_push($results, $project);
                }
            }
        }
        return [
            'total' => count($results),
            'data' => $results,
        ];
    }

    /**
     * @param Project $project
     * @return mixed
     */
    public function usersOf(Project $project) {
        $data = $project->group->users()->where('status', 1)->get(['name', 'isManager', 'status']);
        $total = $data->count();
        return compact('total', 'data');
    }

    public function formatList($user) {
        $project = Project::where('users', $user->_id)->first();
        if (is_null($project)) {
            return ['total' => 0, 'data'=>[]];
        }
        $project->users = [$user];
        return ['total' => 1, 'data' => [$project]];
    }
}